<?php

class FormYamlConfig {
    public static function configFormFromYaml($form, $yaml){
        if (!is_array($yaml)) return;

        if (array_key_exists("widgets", $yaml)){// flat yaml, no dot-grouped widgets
            foreach ($yaml["widgets"] as $widgetKey => $widgetParams){
                self::setWidget($form, $widgetKey, $widgetParams);
            }
        }else{ // dot-grouped widgets
            foreach ($yaml as $rootGroupKey => $rootGroupData){
                $groupTitle=$rootGroupData["label"];
                foreach ($rootGroupData["widgets"] as $widgetKey => $widgetParams){
                    $fieldName="{$rootGroupKey}.{$widgetKey}";
                    self::setWidget($form, $fieldName, $widgetParams);
                }
            }
        }
    }

    private static function setWidget($form, $fieldName, $widgetParams){
        switch ($widgetParams["type"]){
            case "text":
            case "string":
                $widget=new sfWidgetFormInputText();
                $validator=new sfValidatorString(array("required" => false));
                break;
            case "font":
            case "select":
            case "color":
                $choices=$widgetParams["choices"];
                $choicesO=array();
                foreach ($choices as $value){
                    $choicesO[$value]=$value;
                }
                $choices=$choicesO;
                $widget=new sfWidgetFormChoice(array("choices" => $choices));
                $validator=new sfValidatorChoice(array("required" => false, "choices" => $choices));
                break;
            case "file":
                $widget=new sfWidgetFormInputFile();
                $validator=new sfValidatorFile(array("required" => false));
                break;
            case "number":
                $widget=new sfWidgetFormInputText();
                $validator=new sfValidatorString(array("required" => false));
                break;
            case "margins":
                $widget=new sfWidgetFormInputText();
                $validator=new sfValidatorString(array("required" => false));
                break;
        }

        if (empty($widget)){
            return;
        }

        if (!empty($widgetParams["default"])){
            $form->setDefault($fieldName, $widgetParams["default"]);
        }
        
        if (!empty($widgetParams["label"])){
            $widget->setLabel($widgetParams["label"]);
        }

        unset($widgetParams["type"]);
        unset($widgetParams["title"]);
        unset($widgetParams["default"]);
        unset($widgetParams["values"]);
        $widget->setAttributes($widgetParams);

        $form->setWidget($fieldName, $widget);
        $form->setValidator($fieldName, $validator);
    }


}
